import axios from 'axios'
import {Message, MessageBox, Notification} from 'element-ui'
import {setTokenCookie, setTokenCookieTime, removeTokenCookie, getTokenCookie, setCookie, getCookie} from "./auth";
import {ACCESS_TOKEN} from "@/store/mutations-type";
import store from '../store'

let apiBaseUrl = '/nobug';
let expireTime = new Date(new Date().getTime() + 25 * 60 * 1000);
let refresh = "refreshToken";
// 创建axios实例
const service = axios.create({
    baseURL: apiBaseUrl, // api base_url
    timeout: 9000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
    // 拦截所有请求，并将其请求头位置加入token信息 - 这里拿去的是vuex中的token- mian.js中将token存入了
    config.headers[ACCESS_TOKEN] = getTokenCookie();
    return config;
}, error => {
    // 如果发生请求异常
    console.log(error);// for debug
    Promise.reject(error);
});

// response拦截器 - 注意经过本次拦截 所有和这个有关的请求返回对象只是统一的返回格式 result{ code message record }
service.interceptors.response.use(
    (response) => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
        const res = response.data;
        let that = this;
        if (res.code !== 200) {
            /* Message({
                 message: res.message,
                 type: 'error',
                 duration: 3 * 1000
             });*/

            // 401:未登录;
            if (res.code === 401) {
                MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log("进行了响应401拦截——————" + new Date());
                    // 移除本地cookie中的token
                    removeTokenCookie();
                    store.commit("SET_TOKEN", null);
                    try {
                        let path = that.$route.path;
                        if (path.indexOf('/home/welcome') === -1) {
                            window.location.reload()
                        }
                    } catch (e) {
                        window.location.reload()
                    }
                })
            }
            return Promise.reject('error');
        } else {
            // 只要请求头中的authentication字段存有信息 则将其存入cookie中
            const token = response.headers.authentication;
            if (token !== null && token !== '' && "undefined" !== typeof token) {
                console.log(token);
                // setTokenCookieTime(token,expireTime);
                setTokenCookie(token);
                store.commit("SET_TOKEN", token);
            }
            return response.data;
        }
    },
    (error) => {
        if (error.response) {
            let data = error.response.data;
            const token = getTokenCookie;
            console.log("------异常响应------", token);
            console.log("------异常响应------", error.response.status);
            switch (error.response.status) {
                case 403:
                    Notification.error({title: '系统提示', message: '您无法访问', duration: 4 * 1000});
                    break;
                case 500:
                    if (token && data.message.contains("Token失效，请重新登录!")) {
                        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                            confirmButtonText: '重新登录',
                            cancelButtonText: '取消',
                            type: 'error'
                        }).then(() => {
                            // 移除cookie中的无效token信息
                            removeTokenCookie();
                            let that = this;
                            try {
                                let path = that.$route.path;
                                if (path.indexOf('/home/welcome') === -1) {
                                    window.location.reload()
                                }
                            } catch (e) {
                                window.location.reload()
                            }
                        });
                        // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
                    }
                    break;
                case 404:
                    Notification.error({title: '系统提示', message: '很抱歉，资源未找到!', duration: 4 * 1000});
                    break;
                case 504:
                    Notification.error({title: '系统提示', message: '未授权，网络超时', duration: 4 * 1000});
                    break;
                case 401:
                    Notification.error({title: '系统提示', message: '未授权，请重新登录', duration: 4 * 1000});
                    if (token) {
                        removeTokenCookie();
                        store.commit("SET_TOKEN", null);
                        setTimeout(() => {
                            window.location.reload()
                        }, 2500);
                    }
                    break;
                default:
                    Notification.error({title: '系统提示', message: '未授权，请重新登录', duration: 4 * 1000});
                    break;
            }
        }
        return Promise.reject(error)
    });

export default service;
